#pragma once
// -------------------------------------------------
// BlinKit - BkBase Library
// -------------------------------------------------
//   File Name: pac_cache.h
// Description: PACCache Class
//      Author: Ziming Li
//     Created: 2022-10-03
// -------------------------------------------------
// Copyright (C) 2022 MingYang Software Technology.
// -------------------------------------------------

#ifndef BLINKIT_BKBASE_PAC_CACHE_H
#define BLINKIT_BKBASE_PAC_CACHE_H

#include <optional>
#include <curl/curl.h>
#include "bk_http.h"
#include "third_party/quickjs/quickjs.h"
#include "third_party/zed/include/zed/mutex.hpp"

namespace zed {
class url;
};

namespace BlinKit {

class PACCache
{
public:
    PACCache(void) = default;
    ~PACCache(void);

    void Initialize(void);

    using Proxy = std::pair<curl_proxytype, std::string>;
    std::optional<Proxy> FindProxyForURL(const std::string &pacURL, const zed::url &reqURL);
private:
    void Reload(const std::string &code);
    void UpdateIfNecessary(const std::string &URL);
    static std::optional<Proxy> ChooseProxy(std::string_view proxy);

    static void BKAPI OnRequestComplete(BkResponse response, void *userData);

    zed::mutex m_mutex;
    std::string m_pacURL;
    JSRuntime *m_rt = nullptr;
    JSContext *m_ctx = nullptr;
};

} // namespace BlinKit

#endif // BLINKIT_BKBASE_PAC_CACHE_H
